package com.sifang.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class ChatClient {

    public static void main(String[] args) throws InterruptedException {

        //客户端只需要一个事件循环组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建客户端启动对象
            //注意客户端使用的不是 ServerBootstrap 而是 Bootstrap
            Bootstrap bootstrap = new Bootstrap();
            /**设置客户端相关参数
             * group：设置线程组
             * channel：使用NioSocketChannel作为客户端通道实现，注意服务端为NioServerSocketChannel
             * handler：创建通道初始化对象，加入客户端处理器
             */
            bootstrap
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            //加入处理器
                            ChannelPipeline pipeline = channel.pipeline();
                            //向pipeline中加入编码器
                            pipeline.addLast(new StringEncoder());
                            //向pipeline中加入解码器
                            pipeline.addLast(new StringDecoder());
                            //向pipeline中加入业务Handler
                            pipeline.addLast(new ChatClientHandler());
                        }
                    });

            //启动客户端去连接服务端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8888).sync();
            //得到channel
            Channel channel = channelFuture.channel();
            System.out.println("=============== " + channel.localAddress().toString().substring(1) + " ==================");
            //客户端发送消息
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String msg = scanner.nextLine();
                //通过客户端把输入内容发送到服务端
                channel.writeAndFlush(msg);
            }
            //对关闭通道进行监听
            // channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

}

